% author: Markus Scherer
% generates diltated image
% input:  img  ... image to dilate
%         sem  ... logical matrix describing structure element
% output: dilated image
function di = midilate(img, sem)
  % initialization 
  si = size(img);
  di = img;
  di(:,:) = 0;
  % dilation works with flipped structure element
  se = mistrel(flipdim(flipdim(sem,1),2));

  % apply dilation for every pixel
  for i = 1:si(1)
    for j = 1:si(2)
      % handling edges
      [iselv  iselh]        = genimgsel  (se, i, j, si);
      [seselv seselh y x]   = genstrelsel(se, i, j, si);

      % copy relvant image section
      itmp = img(iselv, iselh);
      % find maximum of pixel values that lie in structure element
      ma   = max(max(itmp(se.m(seselv, seselh))));
      if isempty(ma)
        ma = -Inf;
      end
      % set current center to maximum and copy back
      ditmp = di(iselv, iselh);
      ditmp(y, x) = ma;
      di(iselv, iselh) = ditmp;
    end
  end
